/*
 * @author Chris
 * @since 2023/2/2 15:46
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/2/2     Chris        the first version
 */

#include "8052.h"

extern void InitLcd1602();

extern void Lcd1602Show(unsigned char x, unsigned char y, unsigned char *buf, unsigned char len);

extern void I2CStart();

extern __sbit I2CWrite(unsigned char dat);

extern void I2CStop();

extern unsigned char I2CReadAck();

extern unsigned char I2CReadNack();

void E2Read(unsigned char *buf, unsigned char addr, unsigned char len);

void BytesToHexString(unsigned char *dst, unsigned char *src, unsigned char len);

void E2Write(unsigned char *buf, unsigned char addr, unsigned char len);

int main() {
    unsigned char buf[5];
    unsigned char str[20];

    InitLcd1602();

    E2Read(buf, 0x90, sizeof(buf));
    BytesToHexString(str, buf, sizeof(buf));
    Lcd1602Show(0, 0, str, 10);

    for (int i = 0; i < sizeof(buf); ++i) {
        buf[i] = buf[i] + 1 + i;
    }

    E2Write(buf, 0x90, sizeof(buf));
    while (1);
}

void BytesToHexString(unsigned char *dst, unsigned char *src, unsigned char len) {
    while (len--) {
        // 高 4 位
        unsigned char tmp = *src >> 4;
        *dst++ = tmp > 9 ? tmp - 10 + 'A' : tmp + '0';

        // 低 4 位
        tmp = *src & 0x0F;
        *dst++ = tmp > 9 ? tmp - 10 + 'A' : tmp + '0';

        src++;
    }
}

void E2Read(unsigned char *buf, unsigned char addr, unsigned char len) {
    do {
        I2CStart();
        if (I2CWrite(0x50 << 1)) {
            break;
        }
        I2CStop();
    } while (1);

    I2CWrite(addr);
    I2CStart();
    I2CWrite((0x50 << 1) | 0x01);
    while (len-- > 1) {
        *buf++ = I2CReadAck();
    }
    *buf = I2CReadNack();
    I2CStop();
}

void E2Write(unsigned char *buf, unsigned char addr, unsigned char len) {
    while (len--) {
        do {
            I2CStart();
            if (I2CWrite(0x50 << 1)) {
                break;
            }
            I2CStop();
        } while (1);
        I2CWrite(addr++);
        I2CWrite(*buf++);
        I2CStop();
    }
}
